package com.mainbo.androidframework.base.view;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;

import android.net.ConnectivityManager;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.mainbo.androidframework.base.receivers.NetStateReceiver;
import com.mainbo.androidframework.utils.LogUtil;


/**
 * Created by lsmtty on 2016/3/3.
 */
public class BaseActivity extends AppCompatActivity {
    protected final String TAG = getClass().getSimpleName();
    private NetStateReceiver netStateReceiver;  //网络状态监听

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(!isTaskRoot()){ //solve bug http://stackoverflow.com/questions/4341600/how-to-prevent-multiple-instances-of-an-activity-when-it-is-launched-with-differ
                          //
            final Intent intent = getIntent();
            if(intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(intent.getAction())){
                finish();
                return;
            }
        }
        LogUtil.i(TAG, "onCreate");
    }

    public void registNetStateReceiver(){
        IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        if(netStateReceiver==null){
            netStateReceiver = new NetStateReceiver();
        }
        this.registerReceiver(netStateReceiver, filter);
    }

    public void unregistNetStateReceiver(){
        if(netStateReceiver!=null){
            this.unregisterReceiver(netStateReceiver);
            netStateReceiver = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.i(TAG, "onStart");
    }




    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.i(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.i(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregistNetStateReceiver();
        LogUtil.i(TAG, "onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.i(TAG, "onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.i(TAG, "onDestory");
    }



    private boolean isTopActivity(){
        boolean isTop = false;
        ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(TAG)){
            isTop = true;
        }
        return isTop;
    }
}
